package com.lexc.watermq.broker.core;


import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * createTime：2025-08-18 10:33
 * description：
 */
public class CommitLogAppendHandler {

    private final MMapFileModelManager mMapFileModelManager = new MMapFileModelManager();

    public void prepareMMapLoading(String topicName) throws IOException {
        MMapFileModel mMapFileModel = new MMapFileModel();
        mMapFileModel.loadFileInMMap(topicName, 0, 1 * 1024 * 1024);
        mMapFileModelManager.put(topicName, mMapFileModel);
    }

    public void appendMsg(String topicName, String content) {
        MMapFileModel mMapFileModel = mMapFileModelManager.get(topicName);
        if (Objects.isNull(mMapFileModel)) {
            throw new RuntimeException("topic is invalid");
        }
        mMapFileModel.writeContent(content.getBytes(StandardCharsets.UTF_8), false);

    }

    public void readMsg(String topicName) {
        MMapFileModel mMapFileModel = mMapFileModelManager.get(topicName);
        if (Objects.isNull(mMapFileModel)) {
            throw new RuntimeException("topic is invalid");
        }
        byte[] readContent = mMapFileModel.readContent(0, 10);
        System.out.println(new String(readContent));
    }
}
